const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../module/resModel')
const blogRouter = (req, res) => {
  //根据不通的路由匹配对应的controller层
  const path = req.path
  const method = req.method
  res.setHeader('Content-Type', 'application/json')

  if (path === '/api/blog/list' && method === 'GET') {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    let data = getList(author, keyword)
    return new SuccessModel(data)
  } else if (path === '/api/blog/new' && method === 'POST') {
    const data = req.body
    console.log(data, '---- 898989 -----')

    if (data.title) return new SuccessModel(newBlog(data))
    else return new ErrorModel('新建博客失败,没有传入数据')
  } else if (path === '/api/blog/detail' && method === 'GET') {
    const id = req.query.id
    if (id) {
      return new SuccessModel(getDetail(id))
    } else return new ErrorModel('获取博客详情失败,没有传入id')
  } else if (path === '/api/blog/update' && method === 'POST') {
    const id = req.query.id
    const data = req.body
    if (id && data.title) return new SuccessModel(updateBlog(id, data))
    return new ErrorModel('更新博客失败,没有传入id')
  } else if (path === '/api/blog/delete' && method === 'POST') {
    const id = req.query.id
    if (id) return new SuccessModel(delBlog(id))
    return new ErrorModel('删除博客失败,没有传入id')
  } else return false
}

module.exports = blogRouter
